<?php

namespace Lib;

use Common;
use Exception;
use HTTP_Request;
use Sdk\lib\Core;
use Sdk\lib\Format;

class Apis {

	const InnerKey = 'WitSdk@2099';

	public static function GetSign($data) {
		return md5(self::InnerKey . serialize($data));
	}

	public static function RequestInnerWit($func, $param) {
		$requestBody = array(
			'func' => $func,
			'param' => $param,
		);
		$requestBody['sign'] = self::GetSign($requestBody);
		$http = new HTTP_Request();
		$domain = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'];
		$http->setURL($domain . Common::getURI('/system/action/apis'));
		$http->setMethod('POST');
		$http->setBody(json_encode($requestBody));
		$response = $http->send();
		if ($response->getStatus() != 200) {
			throw new Exception($func . '() response error status=' . $response->getStatus());
		}
		$responseBody = json_decode($response->getBody(), true);
		if (!$responseBody) {
			return $response->getBody();
		}
		if ($responseBody['errCode']) {
			throw new Exception($func . '() response: ' . $responseBody['message'], $responseBody['errCode']);
		}
		return $responseBody['data'];
	}

	public static function __callStatic($name, $arguments) {
		if (!defined('FROM_HTTP')) {
			return self::RequestInnerWit($name, $arguments);
		}
		list($plugin, $identifier, $interface, $action) = Format::splitName($name);
		if (!Format::checkAppId($plugin) ||
			!Format::checkBranchId($identifier) ||
			!Format::checkController($interface)) {
			throw new Exception('app identifier is invalid');
		}

		if (!$action) {
			$action = 'index';
		} elseif (!Format::checkAction($action)) {
			throw new Exception('app identifier is invalid');
		}

		$interface = ucfirst($interface);
		if (!file_exists($f = ROOT_PATH . '/www/' . $plugin . '/' . $identifier . '/controllers/' . $interface . '.php')) {
			return Core::RequestWit(__CLASS__, $name, $arguments, Core::Type_ApisMethod);
		}

		require_once $f;
		$controllerName = $interface . 'Controller';
		$methodName = $action . 'Interface';
		if (!class_exists($controllerName) || !method_exists($controllerName, $methodName)) {
			throw new Exception('app identifier is invalid');
		}

		try {
			$c = new $controllerName();
			$c->ReturnType = 'return';
			$return = call_user_func_array(array($c, $methodName), $arguments);
			return json_decode($return, true);
		} catch (Exception $e) {
			throw new Exception($e->getMessage(), $e->getCode());
		}
	}

}